<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { Edit, Search, Delete, Plus } from '@element-plus/icons-vue'
import {
  getPolicyList,
  type AmsPolicy,
  addPolicy,
  type AddPolicyDto,
  type UpdatePolicyDto,
  updatePolicy,
  delPolicy,
} from '@/api/ams'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

defineOptions({
  name:"Policy"
})
const searchDto = reactive({
  name: '',
  resCode: '',
})
const tableData = ref<AmsPolicy[]>([])

const showPolicyDialog = ref(false)

const dialogForm = reactive<AmsPolicy>({})

const forceTriggerEvent = ref<string[]>([])
const taskTime = ref([])
const isAddForm = ref(true)

onMounted(() => {
  clickSearchBtn()
})
const clickSearchBtn = () => {
  getPolicyList(searchDto).then((res) => {
    tableData.value = res
  })
}
const clickAddBtn = () => {
  isAddForm.value = true
  dialogForm.name = ''
  dialogForm.description = ''
  dialogForm.resCode = ''
  dialogForm.checkField = ''
  dialogForm.cmd = ''
  dialogForm.args = ''
  dialogForm.workspace = ''
  dialogForm.timeoutDuration = 3
  dialogForm.cycle = 'day'
  dialogForm.num = 1
  dialogForm.times = 2
  dialogForm.impactScope = 1
  forceTriggerEvent.value = []
  showPolicyDialog.value = true
}
const subdialogForm = () => {
  if (isAddForm.value) {
    const addForm: AddPolicyDto = {
      name: dialogForm.name,
      description: dialogForm.description,
      resCode: dialogForm.resCode,
      checkField: dialogForm.checkField,
      cmd: dialogForm.cmd,
      args: dialogForm.args,
      workspace: dialogForm.workspace,
      timeoutDuration: dialogForm.timeoutDuration,
      isBoot: false,
      isDial: false,
      isLogin: false,
      cycle: dialogForm.cycle,
      num: dialogForm.num,
      times: dialogForm.times,
      startTime: dialogForm.startTime,
      endTime: dialogForm.endTime,
      impactScope: dialogForm.impactScope,
    }
    if (dialogForm.times == 1) {
      if (taskTime.value.length != 2) {
        ElMessage({
          message: '一次性任务请选择任务触发时间端',
          type: 'warning',
        })
      } else {
        addForm.startTime = taskTime.value[0].getTime()
        addForm.endTime = taskTime.value[1].getTime()
        addForm.num = 0
        addForm.cycle = ''
      }
    } else {
      addForm.startTime = '0'
      addForm.endTime = '0'
    }
    addForm.isBoot = forceTriggerEvent.value.includes('isBoot')
    addForm.isDial = forceTriggerEvent.value.includes('isDial')
    addForm.isLogin = forceTriggerEvent.value.includes('isLogin')
    console.log(addForm)

    addPolicy(addForm).then(() => {
      showPolicyDialog.value = false
      clickSearchBtn()
    })
  } else {
    const updateForm: UpdatePolicyDto = {
      id: dialogForm.id,
      name: dialogForm.name,
      description: dialogForm.description,
      resCode: dialogForm.resCode,
      checkField: dialogForm.checkField,
      cmd: dialogForm.cmd,
      args: dialogForm.args,
      workspace: dialogForm.workspace,
      timeoutDuration: dialogForm.timeoutDuration,
      isBoot: false,
      isDial: false,
      isLogin: false,
      cycle: dialogForm.cycle,
      num: dialogForm.num,
      times: dialogForm.times,
      startTime: dialogForm.startTime,
      endTime: dialogForm.endTime,
      impactScope: dialogForm.impactScope,
    }
    updateForm.isBoot = forceTriggerEvent.value.includes('isBoot')
    updateForm.isDial = forceTriggerEvent.value.includes('isDial')
    updateForm.isLogin = forceTriggerEvent.value.includes('isLogin')
    if (dialogForm.times == 1) {
      if (taskTime.value.length != 2) {
        ElMessage({
          message: '一次性任务请选择任务触发时间端',
          type: 'warning',
        })
      } else {
        updateForm.startTime = taskTime.value[0].getTime()
        updateForm.endTime = taskTime.value[1].getTime()
        updateForm.num = 0
        updateForm.cycle = ''
      }
    } else {
      updateForm.startTime = '0'
      updateForm.endTime = '0'
    }
    updatePolicy(updateForm).then(() => {
      showPolicyDialog.value = false
      clickSearchBtn()
    })
  }
}
const clickDelPolicy = (id: string) => {
  delPolicy(id).then(() => {
    clickSearchBtn()
  })
}
const clickEdit = (row: AmsPolicy) => {
  isAddForm.value = false
  dialogForm.id = row.id
  dialogForm.name = row.name
  dialogForm.description = row.description
  dialogForm.resCode = row.resCode
  dialogForm.checkField = row.checkField
  dialogForm.cmd = row.cmd
  dialogForm.args = row.args
  dialogForm.workspace = row.workspace
  dialogForm.timeoutDuration = row.timeoutDuration
  dialogForm.cycle = row.cycle
  dialogForm.num = row.num
  dialogForm.times = row.times
  dialogForm.impactScope = row.impactScope
  forceTriggerEvent.value = []
  if (row.isBoot) {
    forceTriggerEvent.value.push('isBoot')
  }
  if (row.isDial) {
    forceTriggerEvent.value.push('isDial')
  }
  if (row.isLogin) {
    forceTriggerEvent.value.push('isLogin')
  }
  showPolicyDialog.value = true
}
</script>

<template>
  <div>
    <el-dialog v-model="showPolicyDialog" :title="isAddForm ? '添加策略' : '更新策略'" width="500">
      <el-form :model="dialogForm" label-width="auto" style="max-width: 600px">
        <el-form-item label="名称">
          <el-input v-model="dialogForm.name" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="dialogForm.description" />
        </el-form-item>
        <el-form-item label="返回码">
          <el-input v-model="dialogForm.resCode" />
        </el-form-item>
        <el-form-item label="检查字段">
          <el-input v-model="dialogForm.checkField" />
        </el-form-item>
        <el-form-item label="插件">
          <el-input v-model="dialogForm.cmd" />
        </el-form-item>
        <el-form-item label="参数">
          <el-input v-model="dialogForm.args" />
        </el-form-item>
        <el-form-item label="工作空间">
          <el-input v-model="dialogForm.workspace" />
        </el-form-item>
        <el-form-item label="超时时间">
          <el-input-number v-model="dialogForm.timeoutDuration" :min="1" :max="100">
            <template #suffix>
              <span>秒</span>
            </template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="强制触发">
          <el-checkbox-group v-model="forceTriggerEvent">
            <el-checkbox value="isBoot" name="type"> 启动时 </el-checkbox>
            <el-checkbox value="isDial" name="type"> 重连时 </el-checkbox>
            <el-checkbox value="isLogin" name="type"> 登录时 </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="策略类型">
          <el-radio-group v-model="dialogForm.times">
            <el-radio :value="1">一次性任务</el-radio>
            <el-radio :value="2">周期性任务</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="任务时间" v-show="dialogForm.times == 1">
          <el-date-picker
            v-model="taskTime"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            date-format="YYYY-MM-DD"
            time-format="hh:mm:ss"
          />
        </el-form-item>
        <el-form-item label="执行间隔" v-show="dialogForm.times == 2">
          <el-radio-group v-model="dialogForm.cycle">
            <el-radio value="minute">分</el-radio>
            <el-radio value="hour">时</el-radio>
            <el-radio value="day">天</el-radio>
            <el-radio value="week">周</el-radio>
            <el-radio value="month">月</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="间隔数值" v-show="dialogForm.times == 2">
          <el-input-number v-model="dialogForm.num" :min="1" :max="10" />
        </el-form-item>
        <el-form-item label="影响范围">
          <el-radio-group v-model="dialogForm.impactScope">
            <el-radio :value="1">全局</el-radio>
            <el-radio :value="2">指定设备</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showPolicyDialog = false">取消</el-button>
          <el-button type="primary" @click="subdialogForm"> 提交 </el-button>
        </div>
      </template>
    </el-dialog>

    <el-row>
      <el-col>
        <el-card>
          <el-row class="mb-5">
            <el-col>
              <el-input
                v-model="searchDto.name"
                class="max-w-xs mr-5"
                placeholder="请输入策略名称"
                clearable
              />
              <el-button type="primary" :icon="Search" @click="clickSearchBtn">查询</el-button>
              <el-button type="primary" :icon="Plus" @click="clickAddBtn">添加</el-button>
            </el-col>
          </el-row>
          <el-table :data="tableData" stripe style="width: 100%" show-overflow-tooltip>
            <el-table-column type="index" width="50" label="#" />
            <el-table-column prop="name" label="名称" />
            <el-table-column prop="cmd" label="指令" width="80" />
            <el-table-column prop="args" label="参数" />
            <el-table-column prop="workspace" label="工作空间" />
            <el-table-column prop="resCode" label="ResCode" />
            <el-table-column label="强制触发时机" width="150">
              <template #default="scope">
                <el-tooltip effect="dark" placement="top">
                  <template #content> 是否需要在服务重启时强制触发 </template>
                  <el-tag :type="scope.row.isBoot ? 'success' : 'info'">重启</el-tag>
                </el-tooltip>
                <el-tooltip effect="dark" placement="top">
                  <template #content> 是否需要在网络波动重连时强制触发 </template>
                  <el-tag :type="scope.row.isDial ? 'success' : 'info'">重连</el-tag>
                </el-tooltip>
                <el-tooltip effect="dark" placement="top">
                  <template #content> 是否需要在用户登录账户时强制触发 </template>
                  <el-tag :type="scope.row.isLogin ? 'success' : 'info'">登录</el-tag>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="times" label="循环类型">
              <template #default="scope">
                {{ scope.row.times == 1 ? '一次性任务' : '周期性任务' }}
              </template>
            </el-table-column>
            <el-table-column label="触发时机">
              <template #default="scope">
                <span v-if="scope.row.times == 1">
                  {{
                    dayjs(new Date(scope.row.startTime * 1000)).format('YYYY-MM-DD') +
                    ' ~ ' +
                    dayjs(new Date(scope.row.endTime * 1000)).format('YYYY-MM-DD')
                  }}
                </span>
                <span v-else>
                  {{ scope.row.num + ' * ' + scope.row.cycle }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="创建时间">
              <template #default="scope">
                {{ dayjs(new Date(scope.row.createdAt * 1000)).format('YYYY-MM-DD HH:mm:ss') }}
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" min-width="100">
              <template #default="scope">
                <el-link :icon="Edit" type="primary" class="mr-3" @click="clickEdit(scope.row)"
                  >修改</el-link
                >
                <el-link
                  :icon="Delete"
                  type="primary"
                  class="mr-3"
                  @click="clickDelPolicy(scope.row.id)"
                  >删除</el-link
                >
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped></style>
